﻿using Application.Adapter;
using Application.Common.Extensions;
using Application.Common.Interface;
using Domain;
using Domain.Enums;
using MediatR;
using Microsoft.AspNetCore.Server.HttpSys;
using Microsoft.Extensions.Caching.Distributed;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Http;
using TouchSocket.Sockets;

namespace Application.App.Command
{
    /// <summary>
    /// 位置上报  升级固件   校准出酒命令
    /// </summary>
    public class SendCommand : IRequest<Result>
    {
        public string DeviceId { get; set; } = "00F42401";
        public DataType CmdType { get; set; } = DataType.位置信息上报应答下;


    }
    public class SendCommandHandle : IRequestHandler<SendCommand, Result>
    {
        private readonly ITcpService tcpService;
        private readonly IDistributedCache cache;
        private readonly ICustomTcpClient customTcpClient;
        public SendCommandHandle(ITcpService tcpService, IDistributedCache cache, ICustomTcpClient customTcpClient)
        {
            this.tcpService = tcpService;
            this.cache = cache;
            this.customTcpClient = customTcpClient;
        }
        public async Task<Result> Handle(SendCommand request, CancellationToken cancellationToken)
        {
            ///方式1
            {
                ////找到设备id对应的socketId索引
                //Consts.ScoketIDToDeviceId.TryGetKey(request.DeviceId, out var socketId);
                ////A50C 16000001 01 01 0064 2E 5A 

                //Consts.CommandPackageLength.TryGetValue(request.CmdType, out var packageLength);

                //var buffer = new List<byte>() { Consts.StartByte, packageLength };
                //buffer.AddRange(request.DeviceId.HexStringToByteArray());
                //buffer.Add(((int)request.CmdType).ToByte());
                //var vaildCode = buffer.GetVaildByteCode();
                //buffer.Add(vaildCode);
                //buffer.Add(Consts.EndByte);
                //tcpService.Send(socketId, buffer.ToArray());
                //return Result.Success;
            }


            ///方式2
            {
                //try
                //{
                //    ////找到设备id对应的socketId索引
                //    Consts.ScoketIDToDeviceId.TryGetKey(request.DeviceId, out var socketId);
                //    if (this.tcpService.SocketClients.TryGetSocketClient(socketId, out var client))
                //    {

                //        Consts.CommandPackageLength.TryGetValue(request.CmdType, out var packageLength);
                //        var buffer = new List<byte>() { Consts.StartByte,packageLength };
                //        buffer.AddRange(request.DeviceId.HexStringToByteArray());
                //        buffer.Add(((int)request.CmdType).ToByte());
                //        var vaildCode = buffer.GetVaildByteCode();
                //        buffer.Add(vaildCode);
                //        buffer.Add(Consts.EndByte);
                //        var result = client.GetWaitingClient(new WaitingOptions() { AdapterFilter = AdapterFilter.AllAdapter, BreakTrigger = true, ThrowBreakException = true }).SendThenResponse(buffer.ToArray(), timeout: 100000);
                //        await Console.Out.WriteLineAsync($"复用socket 获取服务器返回：{Convert.ToHexString(((BetweenAndRequestInfo)result.RequestInfo).Body)}");
                //        return new Result(ResultCode.Success, Convert.ToHexString(((BetweenAndRequestInfo)result.RequestInfo).Body));

                //    }
                //    else
                //    {
                //        return new Result(ResultCode.Error, "没有这个ID");
                //    }
                //}
                //catch (Exception ex)
                //{
                //    return new Result(ResultCode.Error, ex.Message);
                //}
            }


            ///方式3
            {
                Consts.CommandPackageLength.TryGetValue(request.CmdType, out var packageLength);
                var buffer = new List<byte>() { Consts.StartByte, packageLength };
                buffer.AddRange(request.DeviceId.HexStringToByteArray());
                buffer.Add(((int)request.CmdType).ToByte());
                var vaildCode = buffer.GetVaildByteCode();
                buffer.Add(vaildCode);
                buffer.Add(Consts.EndByte);
                Console.WriteLine($"App Send Command Req:{Convert.ToHexString(buffer.ToArray())}");

                customTcpClient.Send(buffer.ToArray());
                return Result.Success;
            }


        }
    }
}
